package com.example.xunai.repository;

import com.example.xunai.entity.ConversationMessage;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ConversationMessageRepository extends JpaRepository<ConversationMessage, Long> {

    // 根据对话ID获取消息，按turn升序排列
    List<ConversationMessage> findByConversationIdOrderByTurnAsc(Long conversationId);

    // 获取对话的最后一条消息的turn（处理null情况）
    @Query("SELECT MAX(cm.turn) FROM ConversationMessage cm WHERE cm.conversationId = :conversationId")
    Integer findLastTurnByConversationId(@Param("conversationId") Long conversationId);

    // 根据对话ID删除所有消息
    void deleteByConversationId(Long conversationId);

    // 检查对话是否存在消息
    boolean existsByConversationId(Long conversationId);
}